package readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo1 {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        CountDownLatch countDownLatch = new CountDownLatch(10);

        //只做写入
        for(int i = 0 ; i < 10 ; i++){
            final int temp = i;
            new Thread(()->{
                myCache.put(String.valueOf(temp),temp+"!");
            },String.valueOf(i)).start();
        }

        //只做读取
        for(int i = 0 ; i < 10 ; i++){
            final int temp = i;
            new Thread(()->{
                myCache.get(String.valueOf(temp));
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        new Thread(()->{
            try {
                countDownLatch.await();
                myCache.getAll();
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
}

//自定义缓存
class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        //加入写锁
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入完成");
        //解锁
        lock.writeLock().unlock();
    }

    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取的："+o);
        System.out.println(Thread.currentThread().getName()+"读取完成");
    }

    public void getAll(){

        System.out.println(map);
    }
}